package com.kt.thread.demo;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Created by tangwy on 2016/3/22.
 */
public class Ticket {
    private final ReentrantLock lock = new ReentrantLock();
    private List<Integer> list = new ArrayList<Integer>();
    private int ticketNO;

    public Ticket() {
        for (int i = 1; i <= 100; i++) {
            list.add(i);
        }
    }

    private void sale() {
        lock.lock();
        System.out.println("线程" + Thread.currentThread().getName() + "获得锁");
        for (; ticketNO < list.size(); ticketNO++) {
            System.out.println("售出票：" + list.get(ticketNO));
        }
        System.out.println("线程" + Thread.currentThread().getName() + "释放锁");
        lock.unlock();

    }

    public void test() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                sale();
            }
        }).start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                sale();
            }
        }).start();
    }
}


